Query Functions
查询函数可以是任何返回promise的函数。返回的promise要么解析数据,要么抛出错误。
下面配置都是可以的:
useQuery({ queryKey: ['todos'], queryFn: fetchAllTodos })
useQuery({ queryKey: ['todos', todoId], queryFn: () => fetchTodoById(todoId) })
useQuery({
queryKey: ['todos', todoId],
queryFn: async () => {
const data = await fetchTodoById(todoId)
return data
},
})
useQuery({
queryKey: ['todos', todoId],
queryFn: ({ queryKey }) => fetchTodoById(queryKey[1]),
})
Handling and Throwing Errors
对于TanStack Query来说,要确定一个查询有错误,查询函数必须抛出或返回一个被拒绝的Promise。查询函数中抛出的任何错误都将保留在查询的error
状态中。
const { error } = useQuery({
queryKey: ['todos', todoId],
queryFn: async () => {
if (somethingGoseWrong) {
throw new Error('抛出错误')
}
if (somethingElseGoseWrong) {
return Promise.reject(new Error('rejected promise'))
}
return data
}
})
在使用 fetch
等默认情况下不会抛出错误的客户端工具时
虽然大多数实用程序(如axios或graphql-request)会自动为不成功的HTTP调用抛出错误,但有些实用程序(如fetch)在默认情况下不会抛出错误。如果是这样的话,你就需要自己扔了。这里有一个简单的方法来实现流行的fetch API:
useQuery({
queryKey: ['todos', todoId],
queryFn: async () => {
const response = await fetch('/todos/' + todoId)
if (!response.ok) {
throw new Error('Network response was not ok')
}
return response.json()
},
})
Query Function Variables
查询键不仅用于唯一标识要获取的数据,而且还可以作为QueryFunctionContext
的一部分方便地传递到查询函数中。虽然并不总是必要的,但如果需要,这可以提取您的查询函数:
function Todos({ status, page }) {
const result = useQuery({
queryKey: ['todos', { status, page }],
queryFn: fetchTodoList,
})
}
// Access the key, status and page variables in your query function!
function fetchTodoList({ queryKey }) {
const [_key, { status, page }] = queryKey
return new Promise()
}
QueryFunctionContext
The QueryFunctionContext
is the object passed to each query function. It consists of:
queryKey: QueryKey
pageParam?: unknown
- only for
Infinite Queries
- 用于获取当前页面的页面参数
- only for
signal?: AbortSignal
- 由TanStack Query提供的AbortSignal实例
- 可用于取消查询
meta: Record<string, unknown> | undefined
- 一个可选字段,您可以填充有关查询的其他信息